<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>认证调试 - 百日行动线索收集系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body { background-color: #f8f9fa; }
        .debug-container { max-width: 800px; margin: 2rem auto; }
        .log-area { background: #1e1e1e; color: #00ff00; padding: 1rem; border-radius: 5px; font-family: monospace; max-height: 400px; overflow-y: auto; }
        .btn-group { margin-bottom: 1rem; }
        .token-display { background: #f8f9fa; padding: 1rem; border-radius: 5px; word-break: break-all; margin-bottom: 1rem; }
    </style>
</head>
<body>
    <div class="debug-container">
        <h3>认证调试工具</h3>
        
        <div class="card mb-3">
            <div class="card-header">
                <h5>当前认证状态</h5>
            </div>
            <div class="card-body">
                <div id="authStatus">检查中...</div>
                <div class="token-display">
                    <strong>当前Token:</strong>
                    <div id="currentToken">无</div>
                </div>
            </div>
        </div>

        <div class="btn-group">
            <button class="btn btn-primary" onclick="testLogin()">测试登录</button>
            <button class="btn btn-success" onclick="testStatistics()">测试统计接口</button>
            <button class="btn btn-warning" onclick="clearToken()">清除Token</button>
            <button class="btn btn-info" onclick="checkAuth()">检查认证</button>
            <button class="btn btn-secondary" onclick="clearLog()">清除日志</button>
        </div>

        <div class="card">
            <div class="card-header">
                <h5>调试日志</h5>
            </div>
            <div class="card-body p-0">
                <div id="logArea" class="log-area"></div>
            </div>
        </div>
    </div>

    <script>
        function log(message, type = 'info') {
            const logArea = document.getElementById('logArea');
            const timestamp = new Date().toLocaleTimeString();
            const color = {
                'info': '#00ff00',
                'error': '#ff0000',
                'warning': '#ffff00',
                'success': '#00ffff'
            }[type] || '#00ff00';
            
            logArea.innerHTML += `<div style="color: ${color}">[${timestamp}] ${message}</div>`;
            logArea.scrollTop = logArea.scrollHeight;
        }

        function clearLog() {
            document.getElementById('logArea').innerHTML = '';
        }

        function updateAuthStatus() {
            const token = localStorage.getItem('adminToken');
            const user = JSON.parse(localStorage.getItem('adminUser') || '{}');
            const statusDiv = document.getElementById('authStatus');
            const tokenDiv = document.getElementById('currentToken');
            
            if (token) {
                statusDiv.innerHTML = `
                    <div class="alert alert-success">
                        <h6>已登录</h6>
                        <p><strong>用户:</strong> ${user.real_name || user.username || '未知'}</p>
                        <p><strong>角色:</strong> ${user.role || '未知'}</p>
                        <p><strong>状态:</strong> ${user.is_active ? '激活' : '禁用'}</p>
                    </div>
                `;
                tokenDiv.textContent = token;
            } else {
                statusDiv.innerHTML = `
                    <div class="alert alert-danger">
                        <h6>未登录</h6>
                        <p>没有找到有效的认证令牌</p>
                    </div>
                `;
                tokenDiv.textContent = '无';
            }
        }

        async function testLogin() {
            log('开始测试登录...', 'info');
            
            try {
                const response = await fetch('/api/admin/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username: 'admin',
                        password: 'newhand'
                    })
                });

                const result = await response.json();
                
                if (response.ok) {
                    log('登录成功！', 'success');
                    log(`Token: ${result.data.token.substring(0, 50)}...`, 'info');
                    
                    localStorage.setItem('adminToken', result.data.token);
                    localStorage.setItem('adminUser', JSON.stringify(result.data.user_info));
                    
                    updateAuthStatus();
                } else {
                    log(`登录失败: ${result.message}`, 'error');
                }
            } catch (error) {
                log(`登录错误: ${error.message}`, 'error');
            }
        }

        async function testStatistics() {
            log('开始测试统计接口...', 'info');
            
            const token = localStorage.getItem('adminToken');
            if (!token) {
                log('错误: 没有找到认证令牌，请先登录', 'error');
                return;
            }

            log(`使用Token: ${token.substring(0, 50)}...`, 'info');

            try {
                const response = await fetch('/api/admin/statistics/overview?period=all', {
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                log(`响应状态: ${response.status} ${response.statusText}`, 'info');

                if (response.ok) {
                    const result = await response.json();
                    log('统计接口调用成功！', 'success');
                    log(`响应数据: ${JSON.stringify(result, null, 2)}`, 'info');
                } else {
                    const errorText = await response.text();
                    log(`统计接口调用失败: ${response.status} ${response.statusText}`, 'error');
                    log(`错误响应: ${errorText}`, 'error');
                    
                    if (response.status === 401) {
                        log('认证失败，可能原因:', 'warning');
                        log('1. Token已过期', 'warning');
                        log('2. Token格式不正确', 'warning');
                        log('3. 用户权限不足', 'warning');
                        log('4. 用户账户被禁用', 'warning');
                        
                        // 尝试刷新token
                        log('尝试刷新Token...', 'info');
                        await refreshToken();
                    }
                }
            } catch (error) {
                log(`统计接口调用错误: ${error.message}`, 'error');
            }
        }

        async function refreshToken() {
            const token = localStorage.getItem('adminToken');
            if (!token) {
                log('无法刷新Token: 没有现有Token', 'error');
                return;
            }

            try {
                const response = await fetch('/api/admin/refresh-token', {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${token}`,
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    log('Token刷新成功！', 'success');
                    localStorage.setItem('adminToken', result.data.token);
                    updateAuthStatus();
                } else {
                    log('Token刷新失败', 'error');
                }
            } catch (error) {
                log(`Token刷新错误: ${error.message}`, 'error');
            }
        }

        function clearToken() {
            localStorage.removeItem('adminToken');
            localStorage.removeItem('adminUser');
            log('Token已清除', 'warning');
            updateAuthStatus();
        }

        function checkAuth() {
            log('检查当前认证状态...', 'info');
            const token = localStorage.getItem('adminToken');
            const user = localStorage.getItem('adminUser');
            
            if (token) {
                log('找到Token', 'success');
                log(`Token长度: ${token.length}`, 'info');
                
                // 尝试解析JWT token
                try {
                    const payload = JSON.parse(atob(token.split('.')[1]));
                    log(`Token载荷: ${JSON.stringify(payload, null, 2)}`, 'info');
                    
                    const now = Math.floor(Date.now() / 1000);
                    if (payload.exp && payload.exp < now) {
                        log('Token已过期！', 'error');
                    } else {
                        log('Token尚未过期', 'success');
                    }
                } catch (e) {
                    log('无法解析Token载荷', 'warning');
                }
            } else {
                log('未找到Token', 'error');
            }
            
            if (user) {
                log(`用户信息: ${user}`, 'info');
            } else {
                log('未找到用户信息', 'warning');
            }
        }

        // 页面加载时更新状态
        document.addEventListener('DOMContentLoaded', function() {
            updateAuthStatus();
            log('认证调试工具已加载', 'info');
            log('提示: 如果统计页面无法加载数据，请使用此工具进行诊断', 'info');
        });
    </script>
</body>
</html> 